package com.clinic.action.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.clinic.entity.param.SessionUser;
import com.clinic.entity.param.SessionData;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

public abstract class AbstractAction extends ActionSupport 
	implements Preparable, ServletRequestAware, ServletResponseAware {

	private static final long serialVersionUID = 6554454097394234580L;
	private static final String SESSION_DATA_KEY = "medi-clinic-session-data-key";
	
	public static class ActionResult {
		public static final String SUCCESS = "success";
		public static final String ERROR = "error";
		public static final String FAILED = "failed";
		public static final String AUTH_FAILED = "auth_failed";
	}
	
	private HttpServletRequest request;
	private HttpServletResponse response;
	private SessionUser loginUser;
	
	@Override
	public void prepare() {
		doPrepare();
	}
	
	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	public SessionUser getLoginUser() {
		if (loginUser == null) {
			initLoginUser();
		}
		return loginUser;
	}

	protected HttpServletRequest getRequest() {
		if (this.request == null) {
			this.request = ServletActionContext.getRequest();
		}
		return this.request;
	}
	
	protected HttpServletResponse getResponse() {
		return this.response;
	}
	
	protected SessionData getSessionData() {
		return (SessionData) getRequest().getSession().getAttribute(SESSION_DATA_KEY);
	}

	protected void setSessionData(SessionData sd) {
		getRequest().getSession().setAttribute(SESSION_DATA_KEY, sd);
	}
	
	private void initLoginUser() {
		SessionData sd = getSessionData();
		if (sd != null && sd.getSessionUser() != null) {
			this.loginUser = sd.getSessionUser();
		} else {
			this.loginUser = new SessionUser();
		}
	}
	
	private void doPrepare() {
		initLoginUser();
	}
	
}
